package org.mybatis.generator.plugins;

import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.PluginAdapter;
import org.mybatis.generator.entity.ColumnMeta;
import org.mybatis.generator.entity.TableMeta;
import org.mybatis.generator.internal.JDBCConnectionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author hedong
 * @version 1.0
 * @date 2020/6/18
 * @since JDK1.8
 */
public class OriginTableMetaPlugin extends PluginAdapter {

    private static final Logger LOGGER = LoggerFactory.getLogger(OriginTableMetaPlugin.class);

    public static final String ORIGIN_TABLE_META = "originTableMeta";

    @Override
    public boolean validate(List<String> warnings) {
        return true;
    }

    @Override
    public void initialized(IntrospectedTable introspectedTable) {
        JDBCConnectionFactory jdbcConnectionFactory = new JDBCConnectionFactory(getContext().getJdbcConnectionConfiguration());
        try {
            Connection connection = jdbcConnectionFactory.getConnection();
            String schema = introspectedTable.getTableConfiguration().getSchema();
            String tableName = introspectedTable.getTableConfiguration().getTableName();

            ResultSet columns = connection.getMetaData().getColumns(null, schema, tableName, "%");

            List<ColumnMeta> columnMetas = new ArrayList<>();
            while (columns.next()) {
                LOGGER.info("表名：" + columns.getString("TABLE_NAME") + "--字段名：" + columns.getString("COLUMN_NAME") + "--字段注释：" + columns.getString("REMARKS") + "--字段数据类型：" + columns.getString("TYPE_NAME"));
                columnMetas.add(new ColumnMeta(columns.getString("COLUMN_NAME"), columns.getString("TYPE_NAME"), columns.getString("REMARKS")));
            }
            TableMeta tableMeta = new TableMeta(tableName, introspectedTable.getRemarks());
            tableMeta.setColumnMetas(columnMetas);
            introspectedTable.setAttribute(ORIGIN_TABLE_META, tableMeta);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        super.initialized(introspectedTable);
    }
}
